package com.example.controller;


import com.example.domain.Userj;
import com.example.domain.Users;
import com.example.service.IUsersService;
import com.example.tools.CreateVerifiCodeImage;
import com.example.tools.JwtHelper;
import com.example.tools.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;



@RestController
@RequestMapping("/sms/system")
public class SysController {

@Autowired
private IUsersService usersService;

//    @ApiOperation("发送验证码")
//    @GetMapping ("/getVerifiCodeImage")
//    public void getVerifiCodeImage(HttpServletRequest request, HttpServletResponse response){
//        //创建图片
//        BufferedImage verifiCodeImage = CreateVerifiCodeImage.getVerifiCodeImage();
//        //生成图片的字符
//        String verifiCode  = new String(CreateVerifiCodeImage.getVerifiCode());
//        //获取session对象
//        HttpSession session = request.getSession();
//        //将验证码存到session中
//        session.setAttribute("verifiCode",verifiCode);
//        // 将验证码图片响应给浏览器
//
//        try {
//            ImageIO.write(verifiCodeImage,"JPEG",response.getOutputStream());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//
//    }

    @ApiOperation("获取用户登录信息")
    @GetMapping("/getInfo")
    public Result getInfo(
            @ApiParam("通过token获得用户")
            @RequestHeader("token") String token
    ) {
        boolean expiration = JwtHelper.isExpiration(token);
        if (expiration) {
            return Result.fail().message("你的token过期，从新请求token");
        }

       //解析得到用户Id
        Integer userId = JwtHelper.getUserId(token).intValue();
        //解析到用户类型
//        Integer userType = JwtHelper.getUserType(token).intValue();
        Map<String,Object> map = new HashMap<>();

        Users use = usersService.selectUsersByUsersId(userId);
//        map.put("userType",userType);
        map.put("user",use);
        use.setPassword("8888888");




        return Result.ok(map);

    }














    @PostMapping("/login")
    public Result postLogin(@RequestBody Userj use){


            Map<String,Object> map = new HashMap<>();



                Users users = usersService.login(use);
                if (users == null) {
                    return Result.fail().message("用户名或密码有误！");
                }else {

                    map.put("token", JwtHelper.createToken(users.getUsersId().longValue()));
                    return Result.ok(map);
                }



//             return Result.fail().message("没有查到用户");

    }





}

